//
//  XPOperationQueue.swift
//  PPApp
//
//  Created by xiaopin on 2024/3/8.
//

import Foundation

class XPOperationQueue {
    private let queue: OperationQueue
        
    /// 自定义队列的最大并发操作数，默认为无限制
    var maxConcurrentOperationCount: Int {
        get {
            return queue.maxConcurrentOperationCount
        }
        set {
            queue.maxConcurrentOperationCount = newValue
        }
    }
    
    /// 队列是否暂停
    var isSuspended: Bool {
        return queue.isSuspended
    }
    
    /// <#Description#>
    /// - Parameter maxConcurrentOperationCount: 最大并发数
    init(maxConcurrentOperationCount: Int? = nil) {
        queue = OperationQueue()
        if let maxCount = maxConcurrentOperationCount {
            self.maxConcurrentOperationCount = maxCount
        }
    }
    
    /// 添加操作到队列中
    /// - Parameter block: <#block description#>
    func addOperation(_ block: @escaping () -> Void) {
        queue.addOperation(block)
    }
    
    /// 添加异步操作到队列中
    /// - Parameter block: <#block description#>
    func addAsyncOperation(_ block: @escaping () -> Void) {
        let operation = BlockOperation(block: block)
        queue.addOperation(operation)
    }
    
    /// 添加带有依赖关系的操作到队列中
    /// - Parameters:
    ///   - block: <#block description#>
    ///   - dependency: <#dependency description#>
    func addOperation(_ block: @escaping () -> Void, dependentOn dependency: Operation) {
        let operation = BlockOperation(block: block)
        operation.addDependency(dependency)
        queue.addOperation(operation)
    }
    
    /// 取消队列中所有操作
    func cancelAllOperations() {
        queue.cancelAllOperations()
    }
    
    /// 暂停队列
    func suspend() {
        queue.isSuspended = true
    }
    
    /// 恢复队列
    func resume() {
        queue.isSuspended = false
    }
}

